﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;

namespace CoolCode.Net
{
    public class EmailSender : ISender
    {
        const int DefaultPort = 25;
        public string Sender { get; set; }
        public string Password { get; set; }
        public bool IsBodyHtml { get; set; }

        public string Server { get; set; }
        public int? Port { get; set; }
        public bool EnableSsl { get; set; }


        public EmailSender()
        {
            this.IsBodyHtml = true;
            this.EnableSsl = false;
            this.Port = DefaultPort;
        }

        public EmailSender(string sender, string password)
            : this()
        {
            this.Sender = sender;
            this.Password = password;
        }


        public EmailSender(string server, string sender, string password)
            : this(sender, password)
        {
            this.Server = server;
        }

        public void Send(string subject, string content, params  string[] recipients)
        {
            Server.ThrowIfNullOrEmpty("Server");
            Sender.ThrowIfNullOrEmpty("Sender");
            Password.ThrowIfNullOrEmpty("Password");
            recipients.ThrowIfNullOrEmpty("recipients");

            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(Sender);
            mail.To.Add(string.Join(",", recipients));
            //mail.Bcc =  ; 
            //mail.Cc =  ; 
            mail.Subject = subject;
            mail.IsBodyHtml = IsBodyHtml;
            mail.Body = content;

            //Attachment attachment = new  Attachment(@"file name"); 
            //mail.Attachments.Add(attachment);             

            SmtpClient client = new SmtpClient();
            client.Credentials = new NetworkCredential(this.Sender, this.Password);
            client.Port = Port ?? DefaultPort;
            client.Host = Server;
            client.EnableSsl = EnableSsl;//经过ssl加密 
            client.Send(mail);
        }
    }
}
